#include "Driver_Flash.h"
#include "Driver_Delay.h"
#include <string.h>

#define FLASH_PAGES_TO_BE_PROTECTED OB_WRP_Pages0to3

void Flash_Write_Protection(void)
{
  uint32_t WRPR_Value = 0xFFFFFFFF, ProtectedPages = 0x0;
  __IO FLASH_Status FLASHStatus = FLASH_COMPLETE;

  FLASH_Unlock();
  FLASH_OB_Unlock();
  FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPERR);
  WRPR_Value = FLASH_OB_GetWRP();
  ProtectedPages = (~WRPR_Value) | FLASH_PAGES_TO_BE_PROTECTED;

  if (((~WRPR_Value) & FLASH_PAGES_TO_BE_PROTECTED) != FLASH_PAGES_TO_BE_PROTECTED)
  {
    FLASHStatus = FLASH_OB_Erase();
    FLASHStatus = FLASH_OB_EnableWRP(ProtectedPages);
    FLASH_OB_Launch();
  }
  FLASH_OB_Lock();
  FLASH_Lock();
}

void Flash_Read_Protection(void)
{
  if (FLASH_OB_GetRDP() == RESET)
  {
    FLASH_Unlock();
    FLASH_OB_Unlock();
    FLASH_OB_RDPConfig(OB_RDP_Level_1);
    FLASH_OB_Launch();
    FLASH_OB_Lock();
    FLASH_Lock();
  }
}

void Flash_Erase(uint32_t addr, uint8_t NbrOfPage)
{
  uint8_t i = 0;
  FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPERR);
  for (i = 0; i < NbrOfPage; i++)
  {
    FLASH_ErasePage(addr + (FLASH_PAGE_SIZE * i));
  }
}

void Flash_Program_Word(uint32_t WriteAddr, uint32_t Data)
{
  if (FLASH_ProgramWord(WriteAddr, Data) != FLASH_COMPLETE)
  {
    while (1)
    {
    }
  }
}

void Flash_Program_HalfWord(uint32_t WriteAddr, uint16_t Data)
{
  if (FLASH_ProgramHalfWord(WriteAddr, Data) != FLASH_COMPLETE)
  {
    while (1)
    {
    }
  }
}

void Flash_Program_Allow(void)
{
  __set_PRIMASK(1);
  Delay_Ms(1);
  FLASH_Unlock();
}

void Flash_Program_Forbid(void)
{
  FLASH_Lock();
  Delay_Ms(1);
  __set_PRIMASK(0);
}

void Flash_Save_Handler(void)
{
  //  if (Flash_Write_Flag == 1)
  //  {
  //    Flash_Write_Flag = 0;
  //    Flash_Program_Allow();
  //    Flash_Erase(0x08005800, 1);
  //    Flash_Program_Word(0x08005800, Flash_Data[0]);
  //    Flash_Program_Word(0x08005804, Flash_Data[1]);
  //    Flash_Program_Word(0x08005808, Flash_Data[2]);
  //    Flash_Program_Word(0x0800580C, Flash_Data[3]);
  //    Flash_Program_Forbid();
  //  }
}
